package org.groupg.practice.io;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class FileConcurrencyControlExample {
    private static final Lock lock = new ReentrantLock();
    private static final File file = new File("path/to/file.txt");
    private static final ThreadPoolExecutor executorService = new ThreadPoolExecutor(10,50,60, TimeUnit.SECONDS,new LinkedBlockingQueue<>());

    public static void main(String[] args) {
        // 启动文件写入任务
        executorService.submit(() -> writeFile());

        // 启动文件读取任务
        executorService.submit(() -> readFile());
    }

    private static void writeFile() {
        lock.lock();
        try (Writer writer = new FileWriter(file)) {
            IOUtils.write("Hello, World!", writer);
            System.out.println("Write operation completed.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private static void readFile() {
        lock.lock();
        try{
            String content = FileUtils.readFileToString(file, "UTF-8");
            System.out.println("Read operation completed: " + content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    // 动态调整线程池大小和监控间隔的方法
    public static void adjustConcurrency(int newPoolSize, long newInterval) {
        // 根据需要调整线程池大小
        if (newPoolSize > executorService.getActiveCount()) {
            for (int i = 0; i < newPoolSize - executorService.getActiveCount(); i++) {
                executorService.submit(() -> {});
            }
        } else {
            // 减少线程池大小的逻辑，需要更复杂的实现，例如使用线程池的拒绝策略或等待任务完成
        }

        // 调整监控间隔的逻辑，这取决于监控的具体实现
        // 例如，如果使用FileAlterationMonitor，可以调用其setInterval方法
    }
}